package com.ddpt.gateway.filter;

import cn.hutool.crypto.digest.MD5;
import com.ddpt.gateway.filter.base.BaseLimitFilter;
import com.ddpt.gateway.filter.config.LimitConfiguration;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.CollectionUtils;
import org.springframework.util.PathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Set;

/**
 * 请求头验签校验
 */
@Slf4j
@Component
@RefreshScope
public class HeaderSignFilter extends BaseLimitFilter implements GlobalFilter, Ordered {

    @Autowired
    private LimitConfiguration configuration;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        if(!configuration.isEnableSign()){
            return chain.filter(exchange);
        }
        PathMatcher matcher = new AntPathMatcher();
        String path = exchange.getRequest().getURI().getPath();
        if(!CollectionUtils.isEmpty(configuration.getNotSignUrl())){
            //判断当前url是否跳过验签限制
            if(configuration.getNotSignUrl().stream().anyMatch(url -> matcher.match(url,path))){
                return chain.filter(exchange);
            }
        }
        Set<String> signUrl = configuration.getSignUrl();
        if(CollectionUtils.isEmpty(signUrl)){
            return chain.filter(exchange);
        }
        if(signUrl.stream().noneMatch(url -> matcher.match(url, path))){
            return chain.filter(exchange);
        }

        //简单验签过滤机器请求
        String timestamp = exchange.getRequest().getHeaders().getFirst("timestamp");
        String noticeStr = exchange.getRequest().getHeaders().getFirst("noticeStr");
        String sign = exchange.getRequest().getHeaders().getFirst("sign");
        long now = System.currentTimeMillis();
        if(StringUtils.isBlank(timestamp)){
            return writeResponse(exchange,HttpStatus.valueOf(configuration.getSignHttpStatus()),configuration.getSignMsg());
        }
        if(timestamp.length() != 13){
            return writeResponse(exchange,HttpStatus.valueOf(configuration.getSignHttpStatus()),configuration.getSignMsg());
        }
        try {
            long time = Long.parseLong(timestamp);
            if(Math.abs(now-time) > configuration.getSignDelaySecond()){
                return writeResponse(exchange,HttpStatus.valueOf(configuration.getSignHttpStatus()),configuration.getSignMsg());
            }
        }catch (Exception e) {
            return writeResponse(exchange,HttpStatus.valueOf(configuration.getSignHttpStatus()),configuration.getSignMsg());
        }
        if(StringUtils.isBlank(noticeStr)){
            return writeResponse(exchange,HttpStatus.valueOf(configuration.getSignHttpStatus()),configuration.getSignMsg());
        }
        //随机16长度大写字符串，进行md5转大写，取md5前8位放随机串前面，后8位放随机串后面
        if(noticeStr.length() != 32){
            return writeResponse(exchange,HttpStatus.valueOf(configuration.getSignHttpStatus()),configuration.getSignMsg());
        }
        String originNoticeStr = noticeStr.substring(8, 24);
        String md5Prefix = noticeStr.substring(0,8);
        String md5Post = noticeStr.substring(24);
        String noticeMd5 = MD5.create().digestHex(originNoticeStr).toUpperCase();
        if(!noticeMd5.startsWith(md5Prefix) || !noticeMd5.endsWith(md5Post)){
            return writeResponse(exchange,HttpStatus.valueOf(configuration.getSignHttpStatus()),configuration.getSignMsg());
        }
        if(StringUtils.isBlank(sign)){
            return writeResponse(exchange,HttpStatus.valueOf(configuration.getSignHttpStatus()),configuration.getSignMsg());
        }
        if(sign.length() != 32){
            return writeResponse(exchange,HttpStatus.valueOf(configuration.getSignHttpStatus()),configuration.getSignMsg());
        }
        //验证签名,就是随机字符串原串+时间戳进行md5
        if(!sign.equals(MD5.create().digestHex(originNoticeStr+timestamp).toUpperCase())){
            return writeResponse(exchange,HttpStatus.valueOf(configuration.getSignHttpStatus()),configuration.getSignMsg());
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return -99;
    }
}
